package org.example.struct.array;

import com.alibaba.fastjson.JSON;

import java.util.*;

/**
 * @author liyishan
 * @date 2023/12/25 10:10
 * @apiNote
 */

public class Test00645FindErrorNums {

    public static void main(String[] args) {
        int[] nums = {1,2,2,4};
        int[] res = findErrorNums(nums);
        System.out.println(JSON.toJSON(res));
    }

    public int[] findErrorNums0(int[] nums) {
        int n = nums.length;
        Arrays.sort(nums);
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < n; i++) {
            set.add(nums[i]);
        }
        int[] res = new int[2];
        for (int i = 1; i <= n; i++) {
            if (!set.contains(i)) {
                res[1] = i;
            }
        }
        for (int i = 0; i < n - 1; i++) {
            if (nums[i] == nums[i + 1]) {
                res[0] = nums[i];
            }
        }
        return res;
    }

    public static int[] findErrorNums(int[] nums) {
        int[] errorNums = new int[2];
        int n = nums.length;
        Arrays.sort(nums);
        int prev = 0;
        for(int i = 0; i < n; i++){
            int curr = nums[i];
            if(curr == prev){
                errorNums[0] = prev;
            }else if(curr - prev > 1){
                errorNums[1] =prev+1;
            }
            prev = curr;
        }
        if(nums[n-1] != n){
            errorNums[1] = n;
        }
        return errorNums;
    }

    public static int[] findErrorNums1(int[] nums) {
        int[] errorNums = new int[2];
        int n = nums.length;
        Map<Integer,Integer> map = new HashMap<>();
        for(int num:nums){
            map.put(num,map.getOrDefault(num,0)+1);
        }
        for(int i = 1; i <= n; i++){
            int count = map.getOrDefault(i,0);
            if(count == 2){
                errorNums[0] = i;
            }else if(count == 0){
                errorNums[1] = i;
            }
        }
        return errorNums;
    }
}
